<?php

namespace addons\facrm\library;
use think\Cache;

/**
 * 自定义风格
 * Class Theme
 * @package addons\facrm\library
 */
class Theme
{
    private static $config = [];
    private static $key="diyfacrmtheme_setting";

    /**
     * 获取配置
     * @return array|bool|false|float|mixed|string
     */
    public static function get()
    {

        if (empty(self::$config)) {
            $model = new \app\admin\model\facrm\Setting();
            $config = $model
                ->where('key',self::$key)->cache(self::$key)
                ->value('values');

            if (!$config){
                //不存在拿默认的
                $config=file_get_contents(self::getConfigFile());
            }

            $config = (array)json_decode($config, true);
            self::$config = $config;
        }
        return self::$config;
    }

    public static function getFirstParam($type='model',$index=0)
    {
        $config = self::get();
        $id = 0;
        if (isset($config['tabbar']['list']) && is_array($config['tabbar']['list'])) {
            if ($type == 'model') {
                preg_match("/(?<=model\=)\d+$/", $config['tabbar']['list'][$index]['path'], $matches);
                if (count($matches) > 0) {
                    $id = $matches[0];
                }
            } else {
                preg_match("/(?<=channel\=)\d+$/", $config['tabbar']['list'][$index]['path'], $matches);
                if (count($matches) > 0) {
                    $id = $matches[0];
                }
            }
        }
        return $id;
    }

    /**
     * 格式处理
     * @param $config
     * @return mixed
     */
    public static function render($config)
    {
        if (!$config) return $config;
        $url = url('/', '', false, true);
        $url = preg_replace("/\/([\w]+)\.php\//i", "/", $url);
        $url = rtrim($url, "/");

        if (isset($config['theme']['logo'])){
            $config['theme']['logo']=preg_match("/^\/assets\/addons/", $config['theme']['logo']) ?
                $url . $config['theme']['logo'] : cdnurl($config['theme']['logo'], true);
        }


        if (isset($config['tabbar']['list']) && is_array($config['tabbar']['list'])) {

            foreach ($config['tabbar']['list'] as $index => &$item) {
                $item['image'] = preg_match("/^\/assets\/addons/", $item['image']) ? $url . $item['image'] : cdnurl($item['image'], true);
                $item['selectedImage'] = preg_match("/^\/assets\/addons/", $item['selectedImage']) ? $url . $item['selectedImage'] : cdnurl($item['selectedImage'], true);
            }
        }
        return $config;
    }

    /**
     * 保存配置
     * @param $config
     * @return bool|false|int
     */
    public static function set($config)
    {

        $model = new \app\admin\model\facrm\Setting();
        $row = $model->detail(self::$key);
        $params=['values'=>$config,'key'=>self::$key];
        if (!$row){
            $params['describe']="移动端主题设置";
            $params['status']=1;
            $result = $model->allowField(true)->save($params);
        }else{
            $result = $row->allowField(true)->save($params);
        }
        self::clearCache();
        self::$config = $config;
        return $result;
    }

    /**
     * 删除配置（恢复默认）
     * @return bool|int
     */
    public static  function  del(){
        $model = new \app\admin\model\facrm\Setting();
        self::clearCache();
        return $model->where('key',self::$key)->delete();
    }
    /**
     * 默认数据
     * @return string
     */
    public static function getConfigFile()
    {
        return ADDON_PATH . 'facrm' . DS . 'data' . DS . 'theme.json';
    }

    /**
     * 清空缓存
     */
    public static function clearCache(){
        Cache::rm(self::$key);
    }
}
